import { login, logout, getInfo, getButtons } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  permission: [],
  userPermission: [],
  userButtons: [],
  imgUrlName: '',
  ajaxUrl: '',
  pwd:''
}

const mutations = {
  setAjaxUrl: (state, ajaxUrl) => {
    state.ajaxUrl = ajaxUrl
  },
  setImgUrlName: (state, imgUrlName) => {
    state.imgUrlName = imgUrlName
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSION: (state, permission) => {
    state.permission = permission
  },
  SETUSERPERMISSION: (state, userPermission) => {
    state.userPermission = userPermission
  },
  SETBUTTONS: (state, btns) => {
    state.userButtons = btns
  },
  SETPWD:(state,pwd) => {
    state.pwd = pwd
  }
}

const actions = {
  setUserPermission({ commit }, userInfo) {
    getInfo().then(response => {
      commit('SETUSERPERMISSION', response.data.permissions)
    })
  },
  // user login
  login({ commit }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        if (response.code === -1) {
          reject('用户名或密码错误!')
          return
        }
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()        
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (response.code === 0) {
          const data = {
            roles: [response.data.roles],
            introduction: response.data.introduction,
            avatar: response.data.avatar,
            name: response.data.name,
            permission: response.data.permissions
          }
          const { roles, name, avatar, introduction, permission } = data

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!')
          }

          commit('SET_ROLES', roles)
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          commit('SET_INTRODUCTION', introduction)
          commit('SET_PERMISSION', permission)
          commit('SETUSERPERMISSION', response.data.permissions)
          resolve(data)
        } else {
          reject('获取权限信息失败!')
          return
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },
  setButtons({ commit, state }) {
    return new Promise((resolve, reject) => {
      getButtons().then(res => {
        // console.log(res.data)
        commit('SETBUTTONS', res.data)
        resolve(res.data)
      })
    }).catch(error => {
      reject(error)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
